############################################################################
# simulation function that estimates deforestation and emission
# with a carbon price
pred_fun_defor <- function(mdl_loss, 
                     mdl_gain_afr,
                     mdl_gain_lat,
                     mdl_gain_asi,
                     dataf, 
                     forest_cv,
                     ag_rev_name, 
                     carbon_name, 
                     carbon_price,
                     biome_cat_df,
                     start_for_cv_bin,
                     npv_carbon_refor_df,
                     soil_carbon_refor_df,
                     npv_soil_carbon_refor_df){
 
  
  #mdl_loss = mdl_loss
  #mdl_gain_afr = mdl_gain_afr
  #mdl_gain_lat = mdl_gain_lat
  #mdl_gain_asi  = mdl_gain_asi
  #dataf = cont_df
  #forest_cv = start_for_cv
  #ag_rev_name = ag_rev_name
  #carbon_name = carbon_name
  #carbon_price = 0
  #biome_cat_df = biome_cat_df
  #start_for_cv_bin = start_for_cv_bin
  #npv_carbon_refor_df = npv_carbon_refor_df
  #soil_carbon_refor_df = soil_carbon_refor_df
  #npv_soil_carbon_refor_df = npv_soil_carbon_refor_df

  #mdl_loss = cont_loss_list
  #mdl_gain = cont_gain_list
  #dataf = cont_df
  #forest_cv = start_for_cv
  #ag_rev_name = ag_rev_name
  #carbon_name = carbon_name
  #carbon_price = carbon_price
  #biome_cat_df = biome_cat_df
  #npv_carbon_refor_df = npv_carbon_refor_df


  ########### loss prediction 
  # calculate carbon revenue 
  carbon_money = ((dataf[, carbon_name] * 3.67) + dataf$soil_crb + dataf$peat_crb) *
    (carbon_price / 9.567)
  
  # create a variable of character variables 
  bio_fix = paste0("F_biome_num", dataf$biome_num_f)
  bio_fix = mdl_loss[match(bio_fix, names(mdl_loss))]
  
  # create a variable of character variables 
  bio_fix = paste0("F_biome_num", dataf$biome_num_f)
  bio_fix = mdl_loss[match(bio_fix, names(mdl_loss))]
  
  cont_fix = paste0("F_cont_num_f", (ifelse(dataf$cont_var == "LatinAmerica", 1,
                                            ifelse(dataf$cont_var == "Africa", 2, 3))))
  cont_fix = mdl_loss[match(cont_fix, names(mdl_loss))]
  
  # calculate biome reforestation category 
  biome_npv_cat = biome_cat_df$biome_cat[match(dataf$biome_num, biome_cat_df$biome_num)]
  cont_cat = ifelse(dataf$cont_var == "LatinAmerica", 1,
                    ifelse(dataf$cont_var == "Africa", 2, 3))
  match_df = data.frame("uni_ID" = dataf$uni_ID,
                        "biome_npv_cat" = biome_npv_cat,
                        "cont_cat" = cont_cat, 
                        stringsAsFactors = FALSE)
  
  npv_refor_val = left_join(match_df, npv_carbon_refor_df, by = c("biome_npv_cat" = "biome_category",
                                                                  "cont_cat" = "contin_cat"))
  npv_refor_val$ind_var = ifelse(is.na(npv_refor_val$biome_npv_cat), 0, 1)
  
  
  # calculate prediction model 
  pred_loss = mdl_loss["(Intercept)"] + 
    mdl_loss[ag_rev_name] * (dataf[,ag_rev_name] - carbon_money)  +
    dataf$elev * mdl_loss["elev"] + 
    dataf$slope * mdl_loss["slope"] + 
    dataf$iucnlow_2000 * mdl_loss["iucnlow_2000"] + 
    dataf$iucnhigh_2000 * mdl_loss["iucnhigh_2000"] + 
    dataf$dis_city_750k_near * mdl_loss["dis_city_750k_near"] + 
    forest_cv * mdl_loss["per_forest_2000"] + 
    (forest_cv^2) * mdl_loss["per_forest_2000_2"] +
    (forest_cv^3) * mdl_loss["per_forest_2000_3"] + 
    (forest_cv^4) * mdl_loss["per_forest_2000_4"] +
    cont_fix + 
    bio_fix
  
  pred_loss <- exp(pred_loss)
  # change deforestation to zero if predicted deforestation is negative (does not occur)
  pred_loss <- ifelse(pred_loss < 0, 0, pred_loss)
  pred_loss <- ifelse(pred_loss > forest_cv, forest_cv - 0, pred_loss)
  
  
  df_mdl_gain_afr = data.frame(t(mdl_gain_afr), stringsAsFactors = FALSE)
  colnames(df_mdl_gain_afr)[12:length(colnames(df_mdl_gain_afr))] = paste0(colnames(df_mdl_gain_afr)[12:length(colnames(df_mdl_gain_afr))], "_afr")
  df_mdl_gain_lat = data.frame(t(mdl_gain_lat), stringsAsFactors = FALSE)
  colnames(df_mdl_gain_lat)[12:length(colnames(df_mdl_gain_lat))] = paste0(colnames(df_mdl_gain_lat)[12:length(colnames(df_mdl_gain_lat))], "_lat")
  df_mdl_gain_asi = data.frame(t(mdl_gain_asi), stringsAsFactors = FALSE)
  colnames(df_mdl_gain_asi)[12:length(colnames(df_mdl_gain_asi))] = paste0(colnames(df_mdl_gain_asi)[12:length(colnames(df_mdl_gain_asi))], "_asi")
  
  df_mdl_gain = bind_rows(df_mdl_gain_afr,
                          df_mdl_gain_lat,
                          df_mdl_gain_asi)
  df_mdl_gain[is.na(df_mdl_gain)] <- 0
  df_mdl_gain$contin_var = c("Africa",
                             "LatinAmerica",
                             "Asia")
  
  # merge the model data frame with the dataf 
  dataf = left_join(dataf, df_mdl_gain, by = c("cont_var" = "contin_var"))
  
  # create the factor variable data.frame
  cont_add = ifelse(dataf$cont_var == "LatinAmerica", "lat",
                    ifelse(dataf$cont_var == "Asia", "asi", "afr"))
  biome_add = dataf$biome_num
  biome_fixed_eff = paste0("F_biome_num_f", biome_add, "_", cont_add)
  biome_fixed_eff = match(biome_fixed_eff, colnames(dataf))
  
  vec_lengt = vector(mode = "numeric", length = length(biome_fixed_eff))
  
  for(vc in 1:length(vec_lengt)){
    
    vec_lengt[vc] = ifelse(is.na(biome_fixed_eff[vc]),
                           NA, 
                           dataf[vc, biome_fixed_eff[vc]])
    
  }
  
  # create soil carbon reforestation data 
  soil_df = data.frame("uni_ID" = dataf$uni_ID,
                       "cont_cat" = cont_cat, 
                       stringsAsFactors = FALSE)
  
  soil_df = left_join(soil_df, npv_soil_carbon_refor_df, by = c("cont_cat" = "match"))
  
  # carbon gain 
  carbon_gain = ((npv_refor_val$discount_rate_10per * 1.26 * 3.67) + 
                   (dataf$soil_crb_ref * soil_df$discount_rate_10per)) * (0 / 9.567) 
  
  # calculate prediction model 
  pred_gain = dataf$X.Intercept. + 
    dataf$agrev_dec_max_00_10.y * (dataf$agrev_dec_max_00_10.x - carbon_gain)  +
    dataf$elev.y * dataf$elev.x + 
    dataf$slope.y * dataf$slope.x + 
    dataf$iucnlow_2000.y * dataf$iucnlow_2000.x + 
    dataf$iucnhigh_2000.y * dataf$iucnhigh_2000.x + 
    dataf$dis_city_750k_near.y * dataf$dis_city_750k_near.x + 
    forest_cv * dataf$per_forest_2000.y + 
    (forest_cv^2) * dataf$per_forest_2000_2.y +
    (forest_cv^3) * dataf$per_forest_2000_3.y + 
    (forest_cv^4) * dataf$per_forest_2000_4.y +
    vec_lengt
  
  pred_gain <- ifelse(is.na(npv_refor_val$ind_var), 0, pred_gain)
  pred_gain <- exp(pred_gain)
  # change deforestation to zero if predicted deforestation is negative (does not occur)
  pred_gain <- ifelse(pred_gain < 0, 0, pred_gain)
  pred_gain <- ifelse(is.na(start_for_cv_bin), 0, pred_gain)
  
  # calculate forest cover
  pred_gain <- ifelse(pred_gain+forest_cv > 1, 1 - forest_cv, pred_gain)
  
  # calculate forest cover
  new_forest_cover = forest_cv - pred_loss + pred_gain
  
  return(list(new_forest_cover, pred_loss, pred_gain))

}

############################################################################
# simulation function that estimates deforestation and emission
# with a carbon price
pred_fun_refor <- function(mdl_loss, 
                           mdl_gain_afr,
                           mdl_gain_lat,
                           mdl_gain_asi,
                           dataf, 
                           forest_cv,
                           ag_rev_name, 
                           carbon_name, 
                           carbon_price,
                           biome_cat_df,
                           start_for_cv_bin,
                           npv_carbon_refor_df,
                           soil_carbon_refor_df,
                           npv_soil_carbon_refor_df){


  
  ########### loss prediction 
  # calculate carbon revenue 
  carbon_money = ((dataf[, carbon_name] * 3.67) + dataf$soil_crb + dataf$peat_crb) *
    (0 / 9.567)
  
  # create a variable of character variables 
  bio_fix = paste0("F_biome_num", dataf$biome_num_f)
  bio_fix = mdl_loss[match(bio_fix, names(mdl_loss))]
  
  cont_fix = paste0("F_cont_num_f", (ifelse(dataf$cont_var == "LatinAmerica", 1,
                                            ifelse(dataf$cont_var == "Africa", 2, 3))))
  cont_fix = mdl_loss[match(cont_fix, names(mdl_loss))]
  
  # calculate biome reforestation category 
  biome_npv_cat = biome_cat_df$biome_cat[match(dataf$biome_num, biome_cat_df$biome_num)]
  cont_cat = ifelse(dataf$cont_var == "LatinAmerica", 1,
                    ifelse(dataf$cont_var == "Africa", 2, 3))
  match_df = data.frame("uni_ID" = dataf$uni_ID,
                        "biome_npv_cat" = biome_npv_cat,
                        "cont_cat" = cont_cat, 
                        stringsAsFactors = FALSE)
  
  npv_refor_val = left_join(match_df, npv_carbon_refor_df, by = c("biome_npv_cat" = "biome_category",
                                                                  "cont_cat" = "contin_cat"))
  npv_refor_val$ind_var = ifelse(is.na(npv_refor_val$biome_npv_cat), 0, 1)
  

  # calculate prediction model 
  pred_loss = mdl_loss["(Intercept)"] + 
    mdl_loss[ag_rev_name] * (dataf[,ag_rev_name] - carbon_money)  +
    dataf$elev * mdl_loss["elev"] + 
    dataf$slope * mdl_loss["slope"] + 
    dataf$iucnlow_2000 * mdl_loss["iucnlow_2000"] + 
    dataf$iucnhigh_2000 * mdl_loss["iucnhigh_2000"] + 
    dataf$dis_city_750k_near * mdl_loss["dis_city_750k_near"] + 
    forest_cv * mdl_loss["per_forest_2000"] + 
    (forest_cv^2) * mdl_loss["per_forest_2000_2"] +
    (forest_cv^3) * mdl_loss["per_forest_2000_3"] + 
    (forest_cv^4) * mdl_loss["per_forest_2000_4"] +
    cont_fix + 
    bio_fix
  
  pred_loss <- exp(pred_loss)
  # change deforestation to zero if predicted deforestation is negative (does not occur)
  pred_loss <- ifelse(pred_loss < 0, 0, pred_loss)
  pred_loss <- ifelse(pred_loss > forest_cv, forest_cv - 0, pred_loss)
  
  
  df_mdl_gain_afr = data.frame(t(mdl_gain_afr), stringsAsFactors = FALSE)
  colnames(df_mdl_gain_afr)[12:length(colnames(df_mdl_gain_afr))] = paste0(colnames(df_mdl_gain_afr)[12:length(colnames(df_mdl_gain_afr))], "_afr")
  df_mdl_gain_lat = data.frame(t(mdl_gain_lat), stringsAsFactors = FALSE)
  colnames(df_mdl_gain_lat)[12:length(colnames(df_mdl_gain_lat))] = paste0(colnames(df_mdl_gain_lat)[12:length(colnames(df_mdl_gain_lat))], "_lat")
  df_mdl_gain_asi = data.frame(t(mdl_gain_asi), stringsAsFactors = FALSE)
  colnames(df_mdl_gain_asi)[12:length(colnames(df_mdl_gain_asi))] = paste0(colnames(df_mdl_gain_asi)[12:length(colnames(df_mdl_gain_asi))], "_asi")
  
  df_mdl_gain = bind_rows(df_mdl_gain_afr,
                          df_mdl_gain_lat,
                          df_mdl_gain_asi)
  df_mdl_gain[is.na(df_mdl_gain)] <- 0
  df_mdl_gain$contin_var = c("Africa",
                             "LatinAmerica",
                             "Asia")
  
  # merge the model data frame with the dataf 
  dataf = left_join(dataf, df_mdl_gain, by = c("cont_var" = "contin_var"))
  
  # create the factor variable data.frame
  cont_add = ifelse(dataf$cont_var == "LatinAmerica", "lat",
                    ifelse(dataf$cont_var == "Asia", "asi", "afr"))
  biome_add = dataf$biome_num
  biome_fixed_eff = paste0("F_biome_num_f", biome_add, "_", cont_add)
  biome_fixed_eff = match(biome_fixed_eff, colnames(dataf))
  
  vec_lengt = vector(mode = "numeric", length = length(biome_fixed_eff))
  
  for(vc in 1:length(vec_lengt)){
    
    vec_lengt[vc] = ifelse(is.na(biome_fixed_eff[vc]),
                           NA, 
                           dataf[vc, biome_fixed_eff[vc]])
    
  }
  
  # create soil carbon reforestation data 
  soil_df = data.frame("uni_ID" = dataf$uni_ID,
                       "cont_cat" = cont_cat, 
                       stringsAsFactors = FALSE)
  
  soil_df = left_join(soil_df, npv_soil_carbon_refor_df, by = c("cont_cat" = "match"))
  
  # carbon gain 
  carbon_gain = ((npv_refor_val$discount_rate_10per * 1.26 * 3.67) + 
                   (dataf$soil_crb_ref * soil_df$discount_rate_10per)) * (carbon_price / 9.567)
  
  # calculate prediction model 
  pred_gain = dataf$X.Intercept. + 
    dataf$agrev_dec_max_00_10.y * (dataf$agrev_dec_max_00_10.x - carbon_gain)  +
    dataf$elev.y * dataf$elev.x + 
    dataf$slope.y * dataf$slope.x + 
    dataf$iucnlow_2000.y * dataf$iucnlow_2000.x + 
    dataf$iucnhigh_2000.y * dataf$iucnhigh_2000.x + 
    dataf$dis_city_750k_near.y * dataf$dis_city_750k_near.x + 
    forest_cv * dataf$per_forest_2000.y + 
    (forest_cv^2) * dataf$per_forest_2000_2.y +
    (forest_cv^3) * dataf$per_forest_2000_3.y + 
    (forest_cv^4) * dataf$per_forest_2000_4.y +
    vec_lengt
  
  pred_gain <- ifelse(is.na(npv_refor_val$ind_var), 0, pred_gain)
  pred_gain <- exp(pred_gain)
  # change deforestation to zero if predicted deforestation is negative (does not occur)
  pred_gain <- ifelse(pred_gain < 0, 0, pred_gain)
  pred_gain <- ifelse(is.na(start_for_cv_bin), 0, pred_gain)
  
  # calculate forest cover
  pred_gain <- ifelse(pred_gain+forest_cv > 1, 1 - forest_cv, pred_gain)
  
  # calculate forest cover
  new_forest_cover = forest_cv - pred_loss + pred_gain
  
  return(list(new_forest_cover, pred_loss, pred_gain))
  
}

glob_model_pred <- function(mdl_loss, 
                            mdl_gain_afr,
                            mdl_gain_lat,
                            mdl_gain_asi,
                            dataf, 
                            forest_cv,
                            year_steps,
                            ag_rev_name, 
                            carbon_name, 
                            carbon_price,
                            npv_carbon_refor_df,
                            biome_cat_df,
                            plant_per_df,
                            carbon_stock_dec_df,
                            soil_carbon_refor_df,
                            npv_soil_carbon_refor_df){

  
  for_cv_list_defor = list()
  for_cv_list_refor = list()
  def_list = list()
  gain_list = list()
  
  for_2000 = dataf$per_all_forest + dataf$per_for_loss
  start_for_cv_bin = ifelse((start_for_cv == 0) & (for_2000 == 0), NA, 1)  
  
  # loop through every decade
  for(yr in 1:length(year_steps)){
    
    
    if(yr == 1){
      
      # create prediction of forest gain and losss
      pred_list_defor = pred_fun_defor(mdl_loss = mdl_loss, 
                                       mdl_gain_afr = mdl_gain_afr,
                                       mdl_gain_lat = mdl_gain_lat,
                                       mdl_gain_asi  = mdl_gain_asi,
                           dataf = cont_df, 
                           forest_cv = start_for_cv,
                           ag_rev_name = ag_rev_name, 
                           carbon_name = carbon_name, 
                           carbon_price = 0,
                           biome_cat_df = biome_cat_df,
                           start_for_cv_bin = start_for_cv_bin,
                           npv_carbon_refor_df = npv_carbon_refor_df,
                           soil_carbon_refor_df = soil_carbon_refor_df,
                           npv_soil_carbon_refor_df = npv_soil_carbon_refor_df)
      
      #### store in the list object
      for_cv_list_defor[[yr]] = pred_list_defor[[1]]
      def_list[[yr]] =  pred_list_defor[[2]]
      
      # create prediction of forest gain and losss
      pred_list_refor = pred_fun_refor(mdl_loss = mdl_loss, 
                                       mdl_gain_afr = mdl_gain_afr,
                                       mdl_gain_lat = mdl_gain_lat,
                                       mdl_gain_asi  = mdl_gain_asi,                                          
                                       dataf = cont_df, 
                                          forest_cv = start_for_cv,
                                          ag_rev_name = ag_rev_name, 
                                          carbon_name = carbon_name, 
                                          carbon_price = 0,
                                          biome_cat_df = biome_cat_df,
                                       start_for_cv_bin = start_for_cv_bin,
                                          npv_carbon_refor_df = npv_carbon_refor_df,
                                       soil_carbon_refor_df = soil_carbon_refor_df,
                                       npv_soil_carbon_refor_df = npv_soil_carbon_refor_df)
      
      #### store in the list object
      for_cv_list_refor[[yr]] = pred_list_refor[[1]]
      gain_list[[yr]] = pred_list_refor[[3]]
      
      
    } else {
  
      # create prediction of forest gain and losss
      pred_list_defor = pred_fun_defor(mdl_loss = mdl_loss, 
                                       mdl_gain_afr = mdl_gain_afr,
                                       mdl_gain_lat = mdl_gain_lat,
                                       mdl_gain_asi  = mdl_gain_asi,                                       
                                       dataf = cont_df, 
                                       forest_cv = for_cv_list_defor[[yr-1]],
                                       ag_rev_name = ag_rev_name, 
                                       carbon_name = carbon_name, 
                                       carbon_price = carbon_price,
                                       biome_cat_df = biome_cat_df,
                                       start_for_cv_bin = start_for_cv_bin,
                                       npv_carbon_refor_df = npv_carbon_refor_df,
                                       soil_carbon_refor_df = soil_carbon_refor_df,
                                       npv_soil_carbon_refor_df = npv_soil_carbon_refor_df)
      
      #### store in the list object
      for_cv_list_defor[[yr]] = pred_list_defor[[1]]
      def_list[[yr]] =  pred_list_defor[[2]]
      
      # create prediction of forest gain and losss
      pred_list_refor = pred_fun_refor(mdl_loss = mdl_loss, 
                                       mdl_gain_afr = mdl_gain_afr,
                                       mdl_gain_lat = mdl_gain_lat,
                                       mdl_gain_asi  = mdl_gain_asi,                                       
                                       dataf = cont_df, 
                                       forest_cv = for_cv_list_refor[[yr-1]],
                                       ag_rev_name = ag_rev_name, 
                                       carbon_name = carbon_name, 
                                       carbon_price = carbon_price,
                                       biome_cat_df = biome_cat_df,
                                       start_for_cv_bin = start_for_cv_bin,
                                       npv_carbon_refor_df = npv_carbon_refor_df,
                                       soil_carbon_refor_df = soil_carbon_refor_df,
                                       npv_soil_carbon_refor_df = npv_soil_carbon_refor_df)
      
      #### store in the list object
      for_cv_list_refor[[yr]] = pred_list_refor[[1]]
      gain_list[[yr]] = pred_list_refor[[3]]
      
      
    }
    
  }
  
  ####################################################################
  # create data.frame
  # calculate biome reforestation category 
  biome_three_var = biome_cat_df$biome_cat[match(dataf$biome_num,
                                                 biome_cat_df$biome_num)]
  # create continent variable
  cont_cat = ifelse(dataf$cont_var == "LatinAmerica", 1,
                    ifelse(dataf$cont_var == "Africa", 2, 3))
  # create match data.frame 
  match_df = data.frame("uni_ID" = dataf$uni_ID,
                        "biome_car_cat" = biome_three_var,
                        "cont_cat" = cont_cat, 
                        stringsAsFactors = FALSE)
  # merge the dataset
  carb_stock_val = left_join(match_df, carbon_stock_dec_df, by = c("biome_car_cat" = "biome_category",
                                                                   "cont_cat" = "contin_cat"))
  carb_stock_val$ind_var = ifelse(is.na(carb_stock_val$biome_car_cat), 0, 1)
  
  
  # calculate biome reforestation category 
  biome_three_var = biome_cat_df$biome_cat[match(dataf$biome_num, biome_cat_df$biome_num)]
  cont_cat = ifelse(dataf$country == "Brazil", 4,
                    ifelse(dataf$country == "Cambodia", 5,
                           ifelse(dataf$country == "Colombia", 6,
                                  ifelse(dataf$country == "Indonesia", 7,
                                         ifelse(dataf$country == "Liberia", 8,
                                                ifelse(dataf$country == "Malaysia", 9,
                                                       ifelse(dataf$country == "Peru", 10,
                                                              ifelse(dataf$cont_var == "LatinAmerica", 1,
                                                                     ifelse(dataf$cont_var == "Africa", 2, 3)))))))))
  
  # create match data.frame 
  match_df = data.frame("uni_ID" = dataf$uni_ID,
                        "biome_car_cat" = biome_three_var,
                        "cont_cat" = cont_cat, 
                        stringsAsFactors = FALSE)
  match_df = left_join(match_df, plant_per_df, by = c("cont_cat"= "contin_cat"))
  
  carb_stock_val = left_join(match_df, carbon_stock_dec_df, by = c("biome_car_cat" = "biome_category",
                                                                   "cont_cat" = "contin_cat"))
  carb_stock_val$ind_var = ifelse(is.na(carb_stock_val$biome_car_cat), 0, 1)
  
  
  # create soil carbon reforestation data 
  soil_df = data.frame("uni_ID" = dataf$uni_ID,
                       "cont_cat" = cont_cat, 
                       stringsAsFactors = FALSE)
  
  soil_df = left_join(soil_df, soil_carbon_refor_df, by = c("cont_cat" = "match"))
  
  ####################################################################
  
  
  # calculate forest cover and deforestation in square kilometer
  # also calculate emissions for carbon price scenario and bau scenario
  for_cv_skm_defor_list <- lapply(for_cv_list_defor, function(x) x * cont_df$shp_size) 
  def_cv_skm_list <- lapply(def_list, function(x) x * cont_df$shp_size) 
  def_emiss_list <- lapply(def_list, function(x) x * cont_df$shp_size * ((cont_df[, carbon_name] * 3.67 * 100) + 
                                                                           (cont_df$soil_crb * 100) + (cont_df$peat_crb * 100)))  
  # gain square kilometer list
  for_cv_skm_refor_list <- lapply(for_cv_list_refor, function(x) x * cont_df$shp_size) 
  gain_cv_skm_list <- lapply(gain_list, function(x) x * cont_df$shp_size * carb_stock_val$ind_var) 
  gain_emiss_list <- list()
  
  for(gc in 1:length(year_steps)){
    
    #xx = gain_list[[x]] * cont_df$shp_size * 100
    #yy = carb_stock_val$ind_var * carb_df[,x] * 1.26 *  3.67
    #zz = cont_df$soil_crb_ref * soil_df$discount_rate_10per
    
    carb_df = data.frame(carb_stock_val[, as.character(rev(1:gc))])
    gain_emiss_list[[gc]] <- apply(sapply(1:gc, function(x) gain_list[[x]] * 
                                            cont_df$shp_size * 
                                            100 * 
                                            ((carb_stock_val$ind_var *
                                                carb_df[,x] * 
                                                1.26 *
                                                3.67) + 
                                               (cont_df$soil_crb_ref * soil_df$discount_rate_10per))), 1, sum, na.rm = T) 
    
    ###+ (gain_list[[gc]] * cont_df$shp_size *  carb_stock_val$ind_var * 100 *
    ###     (dataf$soil_crb_ref * (match_df$nonplant * 0.21 + match_df$plant * 0.0085)))
    
    
  }
  
  
  # create a set of data frames 
  for_cv_skm_defor_df = as.data.frame(do.call(cbind, for_cv_skm_defor_list))
  def_cv_skm_df = as.data.frame(do.call(cbind, def_cv_skm_list))
  def_emiss_df = as.data.frame(do.call(cbind, def_emiss_list))
  for_cv_skm_refor_df = as.data.frame(do.call(cbind, for_cv_skm_refor_list))
  gain_cv_skm_df  = as.data.frame(do.call(cbind, gain_cv_skm_list))
  gain_emiss_df  = as.data.frame(do.call(cbind, gain_emiss_list))
  
  gain_df = (cont_df$per_for_gain * cont_df$shp_size * 100) * 
    ((1.26 *
        carb_stock_val$ind_var *
        3.67 * 
        carb_stock_val[, c("2", "3", "4", "5")]) +
       (cont_df$soil_crb_ref * soil_df$discount_rate_10per))
  colnames(gain_df) = colnames(gain_emiss_df)
  
  gain_emiss_df = data.frame(as.matrix(gain_emiss_df) + as.matrix(gain_df), stringsAsFactors = FALSE)
  
  
  # set column names 
  colnames(for_cv_skm_defor_df) = year_steps
  colnames(def_cv_skm_df) = year_steps
  colnames(def_emiss_df) = year_steps
  colnames(for_cv_skm_refor_df) = year_steps
  colnames(gain_cv_skm_df) = year_steps
  colnames(gain_emiss_df) = year_steps
  
  # create uni id and add continent and country 
  for_cv_skm_defor_df$uni_ID = cont_df$uni_ID
  for_cv_skm_defor_df$country = cont_df$country
  for_cv_skm_defor_df$continent = cont_df$cont_var
  
  def_cv_skm_df$uni_ID = cont_df$uni_ID
  def_cv_skm_df$country = cont_df$country
  def_cv_skm_df$continent = cont_df$cont_var
  
  def_emiss_df$uni_ID = cont_df$uni_ID
  def_emiss_df$country = cont_df$country
  def_emiss_df$continent = cont_df$cont_var
  
  for_cv_skm_refor_df$uni_ID = cont_df$uni_ID
  for_cv_skm_refor_df$country = cont_df$country
  for_cv_skm_refor_df$continent = cont_df$cont_var
  
  gain_cv_skm_df$uni_ID = cont_df$uni_ID
  gain_cv_skm_df$country = cont_df$country
  gain_cv_skm_df$continent = cont_df$cont_var
  
  gain_emiss_df$uni_ID = cont_df$uni_ID
  gain_emiss_df$country = cont_df$country
  gain_emiss_df$continent = cont_df$cont_var
  
  return(list(for_cv_skm_defor_df,
              def_cv_skm_df,
              def_emiss_df,
              for_cv_skm_refor_df,
              gain_cv_skm_df,
              gain_emiss_df))
  
  
  
  
}

library(dplyr)
library(tidyr)

###############################################################################
# set file folder
fold_path = "D:/Research/global_refor_mac/results/rds_reg_files/"

# upload simulation regressions and dataframe for all three continents
cont_loss_list <- readRDS(paste0(fold_path, "reg_loss_cont_v1.rds"))
cont_loss_list <- cont_loss_list$coefficients
cont_loss_list[is.na(cont_loss_list)] <- 0
# upload simulation regressions and dataframe for all three continents
afr_cont_gain_list <- readRDS(paste0(fold_path, "reg_gain_cont_v1_afr.rds"))
lat_cont_gain_list <- readRDS(paste0(fold_path, "reg_gain_cont_v1_lat.rds"))
asi_cont_gain_list <- readRDS(paste0(fold_path, "reg_gain_cont_v1_asi.rds"))

afr_cont_gain_list <- afr_cont_gain_list$coefficients
afr_cont_gain_list[is.na(afr_cont_gain_list)] <- 0

lat_cont_gain_list <- lat_cont_gain_list$coefficients
lat_cont_gain_list[is.na(lat_cont_gain_list)] <- 0

asi_cont_gain_list <- asi_cont_gain_list$coefficients
asi_cont_gain_list[is.na(asi_cont_gain_list)] <- 0

cont_df <-  readRDS(paste0(fold_path, "all_cont_reg.rds"))
cont_df$carbon_baccini <- cont_df$carbon_baccini * 1.26 / 2 # adjust to carbon and divide by two 
cont_df$peat_crb <- (cont_df$peat_crb / 815.545) * 1782 # change peat CO2 to "new" peat value
cont_df$soil_crb_ref <- (1 / 0.085) * cont_df$soil_crb

# read in biome category dataset
biome_cat = read.csv("D:/Research/global_refor_mac/data/carbon_file/biome_cat.csv",
                     stringsAsFactors = FALSE)
npv_carbon_refor = read.csv("D:/Research/global_refor_mac/data/carbon_file/npv_carbon_refor_trans_new.csv",
                            stringsAsFactors = FALSE)

# read in the carbon stock per decade
carbon_stock_dec = read.csv("D:/Research/global_refor_mac/data/carbon_file/carbon_stock_per_decade_new.csv",
                            stringsAsFactors = FALSE)
colnames(carbon_stock_dec)[4:13] = 1:10

# read in soil npv carbon refor
soil_carbon_refor = read.csv("D:/Research/global_refor_mac/data/carbon_file/soil_carbon_stock_per_decade.csv",
                             stringsAsFactors = FALSE)
npv_soil_carbon_refor = read.csv("D:/Research/global_refor_mac/data/carbon_file/npv_soil_carbon_stock_per_decade.csv",
                                 stringsAsFactors = FALSE)

# read in the carbon stock per decade
plant_per = read.csv("D:/Research/global_refor_mac/data/carbon_file/plant_perc.csv",
                     stringsAsFactors = FALSE)




##################################################################################
#### create bau scenario 

# adjust the data.frame
cont_df = cont_df[which(is.na(cont_df$carbon_baccini) == FALSE), ]
cont_df$soil_crb[is.na(cont_df$soil_crb)] <- 0
cont_df$peat_crb[is.na(cont_df$peat_crb)] <- 0
start_for_cv = cont_df$per_all_forest + cont_df$per_for_loss




#### Zero dollars
glob_model_0dollar <- glob_model_pred(mdl_loss = cont_loss_list, 
                                      mdl_gain_afr = afr_cont_gain_list,
                                      mdl_gain_lat = lat_cont_gain_list,
                                      mdl_gain_asi = asi_cont_gain_list,
                                      dataf = cont_df, 
                                      forest_cv = start_for_cv,
                                      year_steps = seq(2020, 2050, 10),
                                      ag_rev_name = "agrev_dec_max_00_10", 
                                      carbon_name = "carbon_baccini", 
                                      carbon_price = 0,
                                      npv_carbon_refor_df = npv_carbon_refor,
                                      biome_cat_df = biome_cat,
                                      plant_per_df = plant_per,
                                      carbon_stock_dec_df = carbon_stock_dec,
                                      soil_carbon_refor_df = soil_carbon_refor,
                                      npv_soil_carbon_refor_df = npv_soil_carbon_refor)

#### Zero dollars
glob_model_5dollar <- glob_model_pred(mdl_loss = cont_loss_list, 
                                      mdl_gain_afr = afr_cont_gain_list,
                                      mdl_gain_lat = lat_cont_gain_list,
                                      mdl_gain_asi = asi_cont_gain_list,                                      
                                      dataf = cont_df, 
                                      forest_cv = start_for_cv,
                                      year_steps = seq(2020, 2050, 10),
                                      ag_rev_name = "agrev_dec_max_00_10", 
                                      carbon_name = "carbon_baccini", 
                                      carbon_price = 5,
                                      npv_carbon_refor_df = npv_carbon_refor,
                                      biome_cat_df = biome_cat,
                                      plant_per_df = plant_per,
                                      carbon_stock_dec_df = carbon_stock_dec,
                                      soil_carbon_refor_df = soil_carbon_refor,
                                      npv_soil_carbon_refor_df = npv_soil_carbon_refor)

#### Zero dollars
glob_model_10dollar <- glob_model_pred(mdl_loss = cont_loss_list, 
                                       mdl_gain_afr = afr_cont_gain_list,
                                       mdl_gain_lat = lat_cont_gain_list,
                                       mdl_gain_asi = asi_cont_gain_list,                                      
                                       dataf = cont_df, 
                                      forest_cv = start_for_cv,
                                      year_steps = seq(2020, 2050, 10),
                                      ag_rev_name = "agrev_dec_max_00_10", 
                                      carbon_name = "carbon_baccini", 
                                      carbon_price = 10,
                                      npv_carbon_refor_df = npv_carbon_refor,
                                      biome_cat_df = biome_cat,
                                      carbon_stock_dec_df = carbon_stock_dec,
                                      plant_per_df = plant_per,
                                      soil_carbon_refor_df = soil_carbon_refor,
                                      npv_soil_carbon_refor_df = npv_soil_carbon_refor)

#### Zero dollars
glob_model_20dollar <- glob_model_pred(mdl_loss = cont_loss_list, 
                                       mdl_gain_afr = afr_cont_gain_list,
                                       mdl_gain_lat = lat_cont_gain_list,
                                       mdl_gain_asi = asi_cont_gain_list,                                         
                                       dataf = cont_df, 
                                      forest_cv = start_for_cv,
                                      year_steps = seq(2020, 2050, 10),
                                      ag_rev_name = "agrev_dec_max_00_10", 
                                      carbon_name = "carbon_baccini", 
                                      carbon_price = 20,
                                      npv_carbon_refor_df = npv_carbon_refor,
                                      biome_cat_df = biome_cat,
                                      plant_per_df = plant_per,
                                      carbon_stock_dec_df = carbon_stock_dec,
                                      soil_carbon_refor_df = soil_carbon_refor,
                                      npv_soil_carbon_refor_df = npv_soil_carbon_refor)

#### Zero dollars
glob_model_30dollar <- glob_model_pred(mdl_loss = cont_loss_list, 
                                       mdl_gain_afr = afr_cont_gain_list,
                                       mdl_gain_lat = lat_cont_gain_list,
                                       mdl_gain_asi = asi_cont_gain_list,                                         
                                       dataf = cont_df, 
                                      forest_cv = start_for_cv,
                                      year_steps = seq(2020, 2050, 10),
                                      ag_rev_name = "agrev_dec_max_00_10", 
                                      carbon_name = "carbon_baccini", 
                                      carbon_price = 30,
                                      npv_carbon_refor_df = npv_carbon_refor,
                                      biome_cat_df = biome_cat,
                                      plant_per_df = plant_per,
                                      carbon_stock_dec_df = carbon_stock_dec,
                                      soil_carbon_refor_df = soil_carbon_refor,
                                      npv_soil_carbon_refor_df = npv_soil_carbon_refor)

#### Zero dollars
glob_model_40dollar <- glob_model_pred(mdl_loss = cont_loss_list, 
                                       mdl_gain_afr = afr_cont_gain_list,
                                       mdl_gain_lat = lat_cont_gain_list,
                                       mdl_gain_asi = asi_cont_gain_list,                                         
                                       dataf = cont_df, 
                                      forest_cv = start_for_cv,
                                      year_steps = seq(2020, 2050, 10),
                                      ag_rev_name = "agrev_dec_max_00_10", 
                                      carbon_name = "carbon_baccini", 
                                      carbon_price = 40,
                                      npv_carbon_refor_df = npv_carbon_refor,
                                      biome_cat_df = biome_cat,
                                      plant_per_df = plant_per,
                                      carbon_stock_dec_df = carbon_stock_dec,
                                      soil_carbon_refor_df = soil_carbon_refor,
                                      npv_soil_carbon_refor_df = npv_soil_carbon_refor)

#### Zero dollars
glob_model_50dollar <- glob_model_pred(mdl_loss = cont_loss_list, 
                                       mdl_gain_afr = afr_cont_gain_list,
                                       mdl_gain_lat = lat_cont_gain_list,
                                       mdl_gain_asi = asi_cont_gain_list,                                          
                                       dataf = cont_df, 
                                       forest_cv = start_for_cv,
                                       year_steps = seq(2020, 2050, 10),
                                       ag_rev_name = "agrev_dec_max_00_10", 
                                       carbon_name = "carbon_baccini", 
                                       carbon_price = 50,
                                       npv_carbon_refor_df = npv_carbon_refor,
                                       biome_cat_df = biome_cat,
                                       plant_per_df = plant_per,
                                       carbon_stock_dec_df = carbon_stock_dec,
                                       soil_carbon_refor_df = soil_carbon_refor,
                                       npv_soil_carbon_refor_df = npv_soil_carbon_refor)

#### Zero dollars
glob_model_60dollar <- glob_model_pred(mdl_loss = cont_loss_list, 
                                       mdl_gain_afr = afr_cont_gain_list,
                                       mdl_gain_lat = lat_cont_gain_list,
                                       mdl_gain_asi = asi_cont_gain_list,                                          
                                       dataf = cont_df, 
                                       forest_cv = start_for_cv,
                                       year_steps = seq(2020, 2050, 10),
                                       ag_rev_name = "agrev_dec_max_00_10", 
                                       carbon_name = "carbon_baccini", 
                                       carbon_price = 60,
                                       npv_carbon_refor_df = npv_carbon_refor,
                                       biome_cat_df = biome_cat,
                                       plant_per_df = plant_per,
                                       carbon_stock_dec_df = carbon_stock_dec,
                                       soil_carbon_refor_df = soil_carbon_refor,
                                       npv_soil_carbon_refor_df = npv_soil_carbon_refor)


#### Zero dollars
glob_model_70dollar <- glob_model_pred(mdl_loss = cont_loss_list, 
                                       mdl_gain_afr = afr_cont_gain_list,
                                       mdl_gain_lat = lat_cont_gain_list,
                                       mdl_gain_asi = asi_cont_gain_list,                                          
                                       dataf = cont_df, 
                                       forest_cv = start_for_cv,
                                       year_steps = seq(2020, 2050, 10),
                                       ag_rev_name = "agrev_dec_max_00_10", 
                                       carbon_name = "carbon_baccini", 
                                       carbon_price = 70,
                                       npv_carbon_refor_df = npv_carbon_refor,
                                       biome_cat_df = biome_cat,
                                       plant_per_df = plant_per,
                                       carbon_stock_dec_df = carbon_stock_dec,
                                       soil_carbon_refor_df = soil_carbon_refor,
                                       npv_soil_carbon_refor_df = npv_soil_carbon_refor)

#### Zero dollars
glob_model_80dollar <- glob_model_pred(mdl_loss = cont_loss_list, 
                                       mdl_gain_afr = afr_cont_gain_list,
                                       mdl_gain_lat = lat_cont_gain_list,
                                       mdl_gain_asi = asi_cont_gain_list,                                          
                                       dataf = cont_df, 
                                       forest_cv = start_for_cv,
                                       year_steps = seq(2020, 2050, 10),
                                       ag_rev_name = "agrev_dec_max_00_10", 
                                       carbon_name = "carbon_baccini", 
                                       carbon_price = 80,
                                       npv_carbon_refor_df = npv_carbon_refor,
                                       biome_cat_df = biome_cat,
                                       plant_per_df = plant_per,
                                       carbon_stock_dec_df = carbon_stock_dec,
                                       soil_carbon_refor_df = soil_carbon_refor,
                                       npv_soil_carbon_refor_df = npv_soil_carbon_refor)

#### Zero dollars
glob_model_90dollar <- glob_model_pred(mdl_loss = cont_loss_list, 
                                       mdl_gain_afr = afr_cont_gain_list,
                                       mdl_gain_lat = lat_cont_gain_list,
                                       mdl_gain_asi = asi_cont_gain_list,                                          
                                       dataf = cont_df, 
                                       forest_cv = start_for_cv,
                                       year_steps = seq(2020, 2050, 10),
                                       ag_rev_name = "agrev_dec_max_00_10", 
                                       carbon_name = "carbon_baccini", 
                                       carbon_price = 90,
                                       npv_carbon_refor_df = npv_carbon_refor,
                                       biome_cat_df = biome_cat,
                                       plant_per_df = plant_per,
                                       carbon_stock_dec_df = carbon_stock_dec,
                                       soil_carbon_refor_df = soil_carbon_refor,
                                       npv_soil_carbon_refor_df = npv_soil_carbon_refor)

glob_model_100dollar <- glob_model_pred(mdl_loss = cont_loss_list, 
                                        mdl_gain_afr = afr_cont_gain_list,
                                        mdl_gain_lat = lat_cont_gain_list,
                                        mdl_gain_asi = asi_cont_gain_list,                                          
                                        dataf = cont_df, 
                                       forest_cv = start_for_cv,
                                       year_steps = seq(2020, 2050, 10),
                                       ag_rev_name = "agrev_dec_max_00_10", 
                                       carbon_name = "carbon_baccini", 
                                       carbon_price = 100,
                                       npv_carbon_refor_df = npv_carbon_refor,
                                       biome_cat_df = biome_cat,
                                       plant_per_df = plant_per,
                                       carbon_stock_dec_df = carbon_stock_dec,
                                       soil_carbon_refor_df = soil_carbon_refor,
                                       npv_soil_carbon_refor_df = npv_soil_carbon_refor)

############################################################################
### save the model out 
out_path = "D:/Research/global_refor_mac/sensitivity_runs/"

#### create list object data.frame
model_list = list(glob_model_0dollar, glob_model_5dollar, 
                  glob_model_10dollar, glob_model_20dollar, 
                  glob_model_30dollar, glob_model_40dollar, 
                  glob_model_50dollar, glob_model_60dollar, 
                  glob_model_70dollar, glob_model_80dollar, 
                  glob_model_90dollar, glob_model_100dollar)

saveRDS(model_list, paste0(out_path, "glob_model_run_by_cont.rds"))

#for_cv_skm_df,
#def_cv_skm_df,
#def_emiss_df,
#gain_cv_skm_df,
#gain_emiss_df

